package org.supda.system.controller.websocket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;
import org.supda.system.entity.TUser;

/**
 * Socket建立连接（握手）和断开
 */
public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Map<String, Object> attributes) throws Exception {
    	
    	Session session = SecurityUtils.getSubject().getSession();
    	
		System.out.println("Websocket:用户[ID:" +
				session!=null?((TUser)session.getAttribute("userSession")).getAccountName():"" + "]已经建立连接");
		
        // 解决The extension [x-webkit-deflate-frame] is not supported问题
        if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
            request.getHeaders().set("Sec-WebSocket-Extensions",
                    "permessage-deflate");
        }
        
        //拦截得到用户信息
        if (request instanceof ServletServerHttpRequest) {
			ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
			
			//HttpSession session = servletRequest.getServletRequest().getSession(false);
			
			// 标记用户
			Long uid = session!=null?((TUser)session.getAttribute("userSession")).getId():0L;
			
			if(session!=null){
				attributes.put("uid", uid);
			}else{
				return false;
			}
		}
        

        System.out.println("Before Handshake over");
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request,
            ServerHttpResponse response, WebSocketHandler wsHandler,
            Exception ex) {
        System.out.println("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
} 